<!-- 修改对话框结构和交互 -->
<template>
  <el-dialog :visible.sync="dialogVisible" title="编辑选题" @close="handleClose">
    <!-- 状态显示 -->
    <div class="status-section">
      <span>当前状态：</span>
      <el-tag :type="statusTagType(topic.status)">{{ topic.status }}</el-tag>
    </div>

    <!-- 学生ID管理 -->
    <div class="student-management">
      <template v-if="selectedIds.length > 0">
        <h4>已选学生列表：</h4>
        <div class="student-list">
          <div
            v-for="(id, index) in selectedIds"
            :key="index"
            class="student-item"
          >
            <el-tag type="info">{{ id }}</el-tag>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              size="mini"
              @click="removeStudent(index)"
            />
          </div>
        </div>
      </template>

      <!-- 添加学生 -->
      <div class="add-student">
        <el-input
          v-model="newStudentId"
          placeholder="输入学生ID"
          style="width: 200px"
          @keyup.enter.native="addStudent"
        >
          <el-button
            slot="append"
            icon="el-icon-plus"
            @click="addStudent"
          />
        </el-input>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="warning" @click="handleReset">重置已选名单</el-button>
      <el-button :type="topic.status === '已锁定' ? 'success' : 'danger'" @click="toggleLock">
        {{ topic.status === '已锁定' ? '解锁课题' : '锁定课题' }}
      </el-button>
      <el-button type="danger" @click="handleDelete">删除选题</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: ['visible', 'topic'],
  data() {
    return {
      dialogVisible: false, // 本地状态管理
      newStudentId: '',
      selectedIds: []
    }
  },
  watch: {
    dialogVisible(newVal) {
      this.$emit('update:visible', newVal); // 同步父组件状态
    },
    visible(newVal) {
      this.dialogVisible = newVal;
      if (newVal && this.topic) {
        try {
          const rawData = this.topic.selected_students || '[]';
          const parsed = JSON.parse(rawData);
          this.selectedIds = parsed.map(id => String(id));
        } catch (e) {
          console.error('解析学生数据失败:', e);
          this.selectedIds = [];
        }
      }
    }
  },
  methods: {
    // 状态标签类型判断方法
    statusTagType(status) {
      const map = {
        '已发布': 'success',
        '待审核': 'warning',
        '已锁定': 'danger'
      };
      return map[status] || 'info';
    },

    // 添加学生（带校验）
    addStudent() {
      if (!this.newStudentId) return;
      // 校验是否为有效数字
      if (!/^\d+$/.test(this.newStudentId)) {
        this.$message.error('请输入有效的数字ID');
        return;
      }
      // 调用存在性校验接口
      this.$axios.get(`/user/exists/${this.newStudentId}`)
        .then(res => {
          if (res.data.exists) {
            if (!this.selectedIds.includes(this.newStudentId)) {
              this.selectedIds.push(this.newStudentId);
              this.updateSelectedStudents();
              this.newStudentId = '';
            } else {
              this.$message.warning('该学生已存在列表中');
            }
          } else {
            this.$message.error('用户不存在');
          }
        })
        .catch(() => this.$message.error('验证失败'));
    },
    // 删除学生
    removeStudent(index) {
      this.selectedIds.splice(index, 1)
      this.updateSelectedStudents()
    },

    // 更新到后端（关键修改）
    async updateSelectedStudents() {
      try {
        // 构造完整请求体
        const payload = {
          ...this.topic,
          selected_students: JSON.stringify(this.selectedIds), // 直接序列化数组
          maxstudents: 8 - this.selectedIds.length // 实时计算剩余名额
        };

        await this.$axios.put('/topic/update', payload);
        this.$emit('refresh'); // 强制刷新父组件数据
        this.$message.success('更新成功');
      } catch (error) {
        console.error("更新失败:", error.response && error.response.data);
        this.$message.error('更新失败: ' + ((error.response && error.response.data && error.response.data.message) || '未知错误'));
      }
    },

    // 重置已选名单
    async handleReset() {
      try {
        await this.$axios.put('/topic/update', {
          ...this.topic,
          selected_students: '[]', // 清空已选学生
          maxstudents: 8 // 设置为初始值
        });
        this.selectedIds = [];
        this.$emit('refresh');
      } catch (error) {
        this.$message.error('重置失败');
      }
    },

    // 锁定/解锁
    async toggleLock() {
      const newStatus = this.topic.status === '已锁定' ? '已发布' : '已锁定'
      try {
        await this.$axios.put('/topic/update', {
          ...this.topic,
          status: newStatus
        })
        this.topic.status = newStatus
        this.$emit('refresh')
      } catch (error) {
        this.$message.error('操作失败')
      }
    },

    // 删除选题
    handleDelete() {
      this.$confirm('此操作将永久删除该选题，是否继续？', '警告', {
        type: 'warning'
      }).then(async () => {
        await this.$axios.delete(`/topic/${this.topic.topicid}`)
        this.$emit('refresh')
        this.dialogVisible = false
        this.$message.success('删除成功')
      })
    },

    // 关闭对话框
    handleClose() {
      this.$emit('refresh'); // 确保关闭时刷新父组件数据
      this.dialogVisible = false;
    }
  }
}
</script>

<style scoped>
.student-management {
  margin: 20px 0;
}
.student-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 8px 0;
  padding: 8px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.add-student {
  margin-top: 15px;
}
.status-section {
  margin-bottom: 20px;
}
</style>
